package view.transitions;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

public class CheckerBoard extends Animator {
	public static final int	MIN_MOSAIC_SIZE	= 20;
	private int				mosaic_size;
	private BufferedImage	buffer;
	private int				numSquaresVertical;
	private int				numSquaresHorizontal;

	public CheckerBoard(BufferedImage from, BufferedImage to) {
		super(from, new BufferedImage(to.getWidth(), to.getHeight(), BufferedImage.TYPE_INT_ARGB));
		this.buffer = to;
		this.mosaic_size = Math.min(this.overlay.getWidth(), this.overlay.getHeight()) / 10;
		if (MIN_MOSAIC_SIZE > this.mosaic_size) {
			this.mosaic_size = MIN_MOSAIC_SIZE;
		}
		this.numSquaresVertical = this.overlay.getHeight() / this.mosaic_size
				+ ((this.overlay.getHeight() % this.mosaic_size == 0) ? 0 : 1);
		this.numSquaresHorizontal = this.overlay.getWidth() / this.mosaic_size
				+ ((this.overlay.getWidth() % this.mosaic_size == 0) ? 0 : 1);
	}

	@Override
	public void animate() {
		this.currentFrame++;
		Graphics2D g2d = (Graphics2D) this.overlay.getGraphics();
		int x1, y1, x2, y2;
		for (int i = 0; i < this.numSquaresHorizontal; i++) {
			for (int j = 0; j < this.numSquaresVertical; j++) {
				if (MAX_FRAMES / this.currentFrame >= 2) {
					if ((i + j) % 2 == 0) {
						x1 = i * this.mosaic_size + this.mosaic_size * (this.currentFrame * 2 - 2) / Animator.MAX_FRAMES;
						y1 = j * this.mosaic_size;
						x2 = x1 + 2 + this.mosaic_size / Animator.MAX_FRAMES * 2;
						y2 = y1 + this.mosaic_size;
						g2d.drawImage(this.buffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
					}
				} else {
					if ((i + j) % 2 == 1) {
						// x1 = (i+1) * mosaic_size -
						// mosaic_size*(2*(currentFrame-MAX_FRAMES/2)-2)/MAX_FRAMES;
						x1 = i * this.mosaic_size + this.mosaic_size * (2 * (this.currentFrame - Animator.MAX_FRAMES / 2) - 2)
								/ Animator.MAX_FRAMES;
						y1 = j * this.mosaic_size;
						// x2 = x1 -2 - mosaic_size/MAX_FRAMES*2;
						x2 = x1 + 2 + this.mosaic_size / Animator.MAX_FRAMES * 2;
						y2 = y1 + this.mosaic_size;
						g2d.drawImage(this.buffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
					}
				}
			}
		}
	}
}
